package com.shengzai.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

public class ZookeeperDeleteNodeCode {

    public static boolean DeleteAll(ZooKeeper zooKeeper, String paths, String cst) throws IOException, InterruptedException, KeeperException {

        Stat exists = zooKeeper.exists(paths, false);
        if (exists != null) {
//创建一个DeleteAll函数实现递归删除所有节点
            int numChildren = exists.getNumChildren();

            if (numChildren > 0) {
                List<String> children = zooKeeper.getChildren(paths, false);
                for (String child : children) {
                    String tem = paths + "/" + child;
                    DeleteAll(zooKeeper, tem, cst);
                }
            } else {
                zooKeeper.delete(paths, -1);
                System.out.println(paths + "节点已经删除");
            }
        }else {
            return true;
        }

        System.out.println("cst:" + cst);
        Stat exists1 = zooKeeper.exists(cst, false);
        if (exists1 != null) {
            int numChildren1 = exists1.getNumChildren();
            if (numChildren1 == 0) {
                zooKeeper.delete(cst, -1);
                System.out.println(cst + "节点已经删除完毕");
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        };
        ZooKeeper zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181", 1000 * 1000, watcher);
        while (true) {
            boolean b = DeleteAll(zooKeeper, "/second_node", "/second_node");
            if (b) {
                System.out.println("所有子节点已经全部删除完毕");
                break;
            }
        }
        zooKeeper.close();
    }
}
